template.defaults.imports.dateformat = function(time){
    var date = new Date(time)
    var y = date.getFullYear()
    var m = (date.getMonth()+1).toString().padStart(2,0);
    var d = (date.getDate()).toString().padStart(2,0);
    return `${y}-${m}-${d}`
}

// 评论列表功能
$.ajax({
    type:'get',
    url:'/comments',
    success:function(res){
        console.log(res)
        var html = template('commentsTpl',res)
        $('#commentsBox').html(html)

        var pageHtml = template('pageTpl',res)
        $('.pagination').html(pageHtml)
    }
})


function changePage(page){
    $.ajax({
        type:'get',
        url:'/comments',
        data:{
            page:page
        },
        success:function(res){
            console.log(res)
            var html = template('commentsTpl',res)
            $('#commentsBox').html(html)
    
            var pageHtml = template('pageTpl',res)
            $('.pagination').html(pageHtml)
        }
    })
    
}


$('#commentsBox').on("click",'.state',function(){
    var id = $(this).attr('data-id')
    var state = $(this).attr('data-state')
    //让当前的状态反过来一下
    // if(state == 0){
    //     state = 1;
    // }else{
    //     state = 0;
    // }
    state = state == 0 ? 1 : 0;
    $.ajax({
        type:'put',
        url:`/comments/${id}`,
        data:{
            state:state 
        },
        success:function(){
            location.reload()
        }
    })
    console.log(id,state)
})


//用事件委托的方式来实现删除功能
$('#commentsBox').on("click",'.delete',function(){
    var id = $(this).attr('data-id')
    $.ajax({
        type:'delete',
        url:`/comments/${id}`,
        beforeSend:function(){
            if(!confirm('确定要删除吗?')){
                return false;//阻止ajax的发送
            }
        },
        success:function(){
            location.reload()
        }
    })
})